//------------------------------------------------------------------------------
//  BaseBuffer.cpp
//  (C) 2009 xoyojank
//------------------------------------------------------------------------------
#include "StdEddy.h"
#include "Graphics/BaseBuffer.h"


//------------------------------------------------------------------------------
namespace Eddy
{

//------------------------------------------------------------------------------
BaseBuffer::BaseBuffer(BaseBuffer::Usage u, BaseBuffer::Type t)
    : usage(u)
    , type(t)
    , size(0)
{
    glGenBuffers(1, &this->buffer);
}

//------------------------------------------------------------------------------
BaseBuffer::~BaseBuffer()
{
    glDeleteBuffers(1, &this->buffer);
}

//------------------------------------------------------------------------------
inline GLenum
BaseBuffer::GetGLTarget() const
{
    return (Vertex == this->usage) ? GL_ARRAY_BUFFER : GL_ELEMENT_ARRAY_BUFFER;
}

//------------------------------------------------------------------------------
inline GLenum
BaseBuffer::GetGLUsage() const
{
    return (Static == this->usage) ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW;
}

//------------------------------------------------------------------------------
void
BaseBuffer::SetSize(SizeT bufferSize)
{
    assert(0 != bufferSize);
    if (this->GetSize() == bufferSize)
        return;

    this->size = bufferSize;

    // resize the buffer
    glBindBuffer(this->GetGLTarget(), this->buffer);
    glBufferData(this->GetGLTarget(), GLsizeiptr(this->GetSize()), NULL, this->GetGLUsage());
}

//------------------------------------------------------------------------------
void
BaseBuffer::Write(IndexT offset, SizeT dataSize, void* data)
{
    assert(0 != dataSize);
    assert(offset + dataSize <= this->GetSize());
    assert(NULL != data);

    glBindBuffer(this->GetGLTarget(), this->buffer);
    glBufferSubData(this->GetGLTarget(), GLintptr(offset), GLsizeiptr(dataSize), data);
}

}// Eddy
